// pages/members/comments.js
import evn from "../../utils/http/evn"
const api = require('../../utils/http/api')

Page({
  // 跳转到学校详情页面（院校卡片区域点击）
  goSchool(e) {
    const id = e?.currentTarget?.dataset?.schoolId;
    console.log('点击的schoolId:', id);
    if (id) {
      wx.navigateTo({
        url: '/pages/schools/schools?schoolId=' + id,
      })
    } else {
      wx.showToast({ title: '无效schoolId', icon: 'none' });
    }
  },
  data: {
    imgBaseUrl: evn.dev.imgUrl,
    infoCount: 4,
    commentsList: []
  },

  onLoad(options) {
    let userInfo = wx.getStorageSync('userInfo') || {};
    let userId = userInfo.id;
    if (userId) {
      api.apiGetUnreadCountPublic({ userId }).then(count => {
        this.setData({ infoCount: count });
      });
      api.apiGetCommentPublic({ userId }).then(list => {
        let arr = Array.isArray(list.data) ? list.data : (list.data ? [list.data] : []);
        let commentsList = arr.map(item => ({
          id: item.commentId || item.id,
          userAvatar: item.userAvatar ? (item.userAvatar.startsWith('http') ? item.userAvatar : (item.userAvatar)) : (userInfo.avatarUrl ? (userInfo.avatarUrl.startsWith('http') ? userInfo.avatarUrl : (userInfo.avatarUrl)) : (evn.dev.imgUrl + '/touxiang.png')),
          userName: item.userName || userInfo.nickname || '',
          createdAt: item.createdAt ? item.createdAt.split(' ')[0].replace(/-/g, '.') : '',
          title: item.title || '',
          content: item.content || '',
          schoolPics: item.schoolPics ? (item.schoolPics.startsWith('http') ? item.schoolPics : (item.schoolPics)) : '',
          schoolName: item.schoolName || '',
          intro: this.filterHtmlTags(item.intro || ''), // 这里调用过滤
          schoolId: item.objectId || '',
          // 新增图片数组处理，兼容 picsArray 已为数组的情况
          picsArray: Array.isArray(item.picsArray)
            ? item.picsArray.map(pic => pic.startsWith('http') ? pic : ( pic))
            : (item.pics ? item.pics.split(',').map(pic => pic.startsWith('http') ? pic : (pic)) : [])
        }));
        this.setData({ commentsList });
      });
    }
  },

  onShow() {
    // 页面每次显示时都刷新未读消息数
    let userInfo = wx.getStorageSync('userInfo') || {};
    let userId = userInfo.id;
    if (userId) {
      api.apiGetUnreadCountPublic({ userId }).then(count => {
        this.setData({ infoCount: count });
      });
    }
  },

  // 跳转到评论详情页面，schoolName/schoolId取自每条评论
goComments(e) {
  let id = e.currentTarget.dataset.id
  console.log('goComments 传递的 id:', id)
  // if (!id) {
  //   wx.showToast({ title: '评论ID无效', icon: 'none' });
  //   return;
  // }
  const item = this.data.commentsList.find(c => c.id == id)
  wx.navigateTo({
    url: '/pages/schools/comments/info?id=' + id +
      '&schoolName=' + (item ? item.schoolName : '') +
      '&schoolId=' + (item ? item.schoolId : ''),
  })
},

  goBack() {
    wx.navigateBack({ delta: 1 });
  },

  onGotoMessage() {
    wx.navigateTo({ url: '/pages/members/message' });
  },
// 过滤html标签
  filterHtmlTags(html) {
    if (!html) return '';
    return html.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').trim();
  }

})